#include "RobotOther.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>

namespace robokit {

RobotOther::RobotOther(QObject* parent)
    : RobotBase(parent)
{
    // 连接协议错误信号
    connect(&m_protocol, &robokit::RProtocol::errorMessage,
            this, &robokit::RobotOther::getError);

    // 连接状态变化信号
    connect(&m_protocol, &robokit::RProtocol::stateChange,
            this, &robokit::RobotOther::slot_connectionStateChange);
}

bool RobotOther::initConnection()
{
    if (m_protocol.initTcpConnection(QHostAddress(m_defaultAddress), m_defaultTcpPort))
    {
        return true;
    }
    return false;
}

bool RobotOther::initTcpConnection(const QHostAddress& address, const quint16 port)
{
    if (m_protocol.initTcpConnection(address, port))
    {
        return true;
    }
    return false;
}

void RobotOther::setDefaultAddress(const QString& newDefaultAddress)
{
    m_defaultAddress = newDefaultAddress;
}

void RobotOther::setDefaultTcpPort(quint16 newDefaultTcpPort)
{
    m_defaultTcpPort = newDefaultTcpPort;
}

bool RobotOther::checkConnection()
{
    return m_protocol.getProtocolState() != -1 ? false : true;
}

void RobotOther::getError(QString msg)
{
    qWarning() << "[RobotOther] Error:" << msg;
}

// ========== 顶升控制 API 实现 ==========

void RobotOther::robot_other_jack_load_req()
{
    // 顶升上升请求，无JSON数据
    QByteArray emptyData;

    m_protocol.WriteTcpData(
        CMD_JACK_LOAD_REQ,
        emptyData,
        std::bind(&RobotOther::robot_other_jack_load_res_receive,
                  this,
                  std::placeholders::_1,
                  std::placeholders::_2)
    );

    qDebug() << "[RobotOther] Jack load request sent (CMD: 6070)";
}

void RobotOther::robot_other_jack_load_res_receive(uint16_t revCommand, QByteArray& receivedata)
{
    qDebug() << "[RobotOther] Jack load response received (CMD:" << revCommand << ")";

    // 解析响应JSON
    QJsonDocument itemDoc = QJsonDocument::fromJson(receivedata);
    QJsonObject rootObject = itemDoc.object();

    // 提取响应字段
    int ret_code = rootObject.value("ret_code").toInt(0);
    QString create_on = rootObject.value("create_on").toString();
    QString err_msg = rootObject.value("err_msg").toString();

    // 打印调试信息
    qDebug() << "[RobotOther] Jack load result:"
             << "ret_code =" << ret_code
             << ", create_on =" << create_on
             << ", err_msg =" << err_msg;

    // 发出完成信号
    emit jackLoadCompleted(ret_code, err_msg, create_on);
}

void RobotOther::robot_other_jack_unload_req()
{
    // 顶升下降请求，无JSON数据
    QByteArray emptyData;

    m_protocol.WriteTcpData(
        CMD_JACK_UNLOAD_REQ,
        emptyData,
        std::bind(&RobotOther::robot_other_jack_unload_res_receive,
                  this,
                  std::placeholders::_1,
                  std::placeholders::_2)
    );

    qDebug() << "[RobotOther] Jack unload request sent (CMD: 6071)";
}

void RobotOther::robot_other_jack_unload_res_receive(uint16_t revCommand, QByteArray& receivedata)
{
    qDebug() << "[RobotOther] Jack unload response received (CMD:" << revCommand << ")";

    // 解析响应JSON
    QJsonDocument itemDoc = QJsonDocument::fromJson(receivedata);
    QJsonObject rootObject = itemDoc.object();

    // 提取响应字段
    int ret_code = rootObject.value("ret_code").toInt(0);
    QString create_on = rootObject.value("create_on").toString();
    QString err_msg = rootObject.value("err_msg").toString();

    // 打印调试信息
    qDebug() << "[RobotOther] Jack unload result:"
             << "ret_code =" << ret_code
             << ", create_on =" << create_on
             << ", err_msg =" << err_msg;

    // 发出完成信号
    emit jackUnloadCompleted(ret_code, err_msg, create_on);
}

// ========== DO 控制 API 实现 ==========

void RobotOther::robot_other_setdo_req(int id, bool status)
{
    QJsonObject jsonObj;
    jsonObj["id"] = id;
    jsonObj["status"] = status;

    QJsonDocument doc(jsonObj);
    QByteArray jsonData = doc.toJson(QJsonDocument::Compact);

    m_protocol.WriteTcpData(
        CMD_SETDO_REQ,
        jsonData,
        std::bind(&RobotOther::robot_other_setdo_res_receive,
                  this,
                  std::placeholders::_1,
                  std::placeholders::_2)
    );

    qDebug() << "[RobotOther] Set DO request sent (CMD: 6001), id:" << id << ", status:" << status;
}

void RobotOther::robot_other_setdo_res_receive(uint16_t revCommand, QByteArray& receivedata)
{
    qDebug() << "[RobotOther] Set DO response received (CMD:" << revCommand << ")";

    QJsonDocument itemDoc = QJsonDocument::fromJson(receivedata);
    QJsonObject rootObject = itemDoc.object();

    int ret_code = rootObject.value("ret_code").toInt(0);
    QString create_on = rootObject.value("create_on").toString();
    QString err_msg = rootObject.value("err_msg").toString();

    qDebug() << "[RobotOther] Set DO result:"
             << "ret_code =" << ret_code
             << ", create_on =" << create_on
             << ", err_msg =" << err_msg;

    emit setDoCompleted(ret_code, err_msg, create_on);
}

} // namespace robokit
